package com.ithao.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ithao.dao.PermissionDao;
import com.ithao.dao.RoleDao;
import com.ithao.dao.UserDao;
import com.ithao.entity.PageResult;
import com.ithao.entity.QueryPageBean;
import com.ithao.pojo.Permission;
import com.ithao.pojo.Role;
import com.ithao.pojo.User;
import com.ithao.service.UserService;
import com.ithao.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @description ：用户业务实现类
 * @version: 1.0
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {
        log.info("UserServiceImpl findByUsername:{}", username);
        User user = userDao.findByUsername(username);
        if (null == user) { //用户不存在
            return null;
        }

        //根据用户Id查角色信息
        List<Role> roles = roleDao.selectRoleByUserId(user.getId());
        if (roles != null && roles.size() > 0) {
            //根据角色Id查权限信息
            for (Role role : roles) {
                List<Permission> permissions = permissionDao.selectPermissionByRoleId(role.getId());
                if (permissions != null && permissions.size() > 0) {
                    role.setPermissionList(permissions);
                }
            }
            user.setRoleList(roles);
        }
        log.info("[findByUserName] user: {}", user);
        return user;
    }

    @Override
    public List<String> findAuthorityByUserId(Integer userId) {
        List<String> authorityList = new ArrayList<>();
        // 获取角色列表
        List<Role> roles = roleDao.selectRoleByUserId(userId);
        // 获取权限列表
        for (Role role : roles) {
            authorityList.add(role.getKeyword());
            List<Permission> permissions = permissionDao.selectPermissionByRoleId(role.getId());
            for (Permission permission : permissions) {
                authorityList.add(permission.getKeyword());
            }
        }
        return authorityList;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //开启分页
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //查找数据库
        Page<User> page = userDao.selectPage(queryPageBean.getQueryParams());
        //封装rolesName
        ArrayList<User> userArrayList = new ArrayList<>();
        List<User> userList = page.getResult();
        for (User user : userList) {
            StringBuilder nameStr = new StringBuilder();
            List<Role> roleList = user.getRoleList();
            if (roleList != null && roleList.size() > 0) {
                for (Role role : roleList) {
                    nameStr.append(role.getName() + " ");
                }
            }
            user.setRolesName(nameStr.toString());
            userArrayList.add(user);
        }
        log.info("[userList] : {}", userArrayList);
        return new PageResult(page.getTotal(), userArrayList);

    }

    @Override
    public void updateStatus(Integer id, Integer state) {
        userDao.updateState(id, state);
    }

    @Override
    @Transactional
    public void add(User user, Integer[] roleIds) {
        if (user == null) {
            throw new RuntimeException("参数为空");
        }
        //补充User数据
        user.setSource("本地");
        user.setState(1); //默认启用
        user.setCreateDate(DateUtils.parseDate2String(new Date()));

        userDao.insertOne(user);

        //再插User和Role的中间表
        for (Integer roleId : roleIds) {
            userDao.insertUserAndRole(user.getId(), roleId);
        }
    }

    @Override
    @Transactional
    public void delete(Integer id) {
        //先删User和role的中间表
        userDao.deleteUserAndRole(id);
        //再删user
        userDao.delete(id);
    }

    @Override
    public User findById(Integer id) {
        User user = userDao.findById(id);
        return user;
    }

    @Override
    @Transactional
    public void update(User user, Integer[] roleIds) {
        //更新基本数据
        userDao.update(user);
        //删除之前的用户角色Id
        userDao.deleteUserAndRole(user.getId());
        //插入新的角色
        for (Integer roleId : roleIds) {
            userDao.insertUserAndRole(user.getId(), roleId);
        }
    }

    //查找用户选中的角色的Id
    @Override
    public List<Integer> findRolesById(Integer userId) {
        return userDao.findRolesById(userId);
    }
}
